package com.zhilehuo.pretask.adapter

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.zhilehuo.pretask.databinding.ItemCategoryBinding

/**
 * @Description: 分类数据类
 * @Author: Realnt
 * @Date:
 */
data class Category(
    val id: Int,
    val type: String
)

/**
 * @Description: 分类适配器
 * @Author: Realnt
 * @Date:
 */
class CategoryAdapter(
    private val onClick: (Category) -> Unit
) : ListAdapter<Category, CategoryAdapter.ViewHolder>(DiffCallback) {

    var selectedCategory: Category? = Category(0, "精选阅读") // 顶置的精选分类

    /**
     * @Description: 分类的ViewHolder
     * @Author: Realnt
     * @Date:
     */
    inner class ViewHolder(val binding: ItemCategoryBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(item: Category) {
            binding.apply {
                categoryName.text = item.type
                root.setOnClickListener {
                    onClick(item)

                    selectedCategory = item // 更新选中的分类
                    notifyDataSetChanged()
                }

                /* 根据是否选中设置样式 */
                if (selectedCategory?.id == item.id) {
                    categoryName.setTextColor(Color.parseColor("#00A0FF"))
                    llBackground.setBackgroundColor(Color.parseColor("#FFFFFF"))
                    tvIndicator.visibility = View.VISIBLE
                } else {
                    categoryName.setTextColor(Color.BLACK)
                    llBackground.setBackgroundColor(Color.parseColor("#EEEEEE"))
                    tvIndicator.visibility = View.GONE
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        ViewHolder(ItemCategoryBinding.inflate(LayoutInflater.from(parent.context), parent, false))

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
        if (position == 0){ holder.binding.categoryImg.visibility = View.VISIBLE } // 显示精选阅读的图标
    }

    /* 增量更新 */
    object DiffCallback : DiffUtil.ItemCallback<Category>() {
        override fun areItemsTheSame(oldItem: Category, newItem: Category) = oldItem.id == newItem.id
        override fun areContentsTheSame(oldItem: Category, newItem: Category) = oldItem == newItem
    }
}